package com.imooc.user.controller;

import com.imooc.api.controller.user.BaseControllerApi;
import com.imooc.api.controller.user.UserControllerApi;
import com.imooc.grance.result.GraceJsonResult;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.pojo.AppUser;
import com.imooc.pojo.bo.UpdateUserInfoBO;
import com.imooc.pojo.vo.AppUserInfoVO;
import com.imooc.pojo.vo.UserAccountInfoVO;
import com.imooc.user.mapper.AppUserMapper;
import com.imooc.user.service.UserService;
import com.imooc.utils.JsonUtils;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/14/22:17
 * @Description:
 */
@RestController
@DefaultProperties(defaultFallback = "defaultRallback")
public class UserController extends BaseControllerApi implements UserControllerApi {

    @Autowired
    private UserService userService;
    @Autowired
    private AppUserMapper appUserMapper;

    @Value("${server.port}")
    private String myPort;

    /**
     * 全局降级的处理方法
     * @return
     */
    public GraceJsonResult defaultRallback() {
        System.out.println("全局降级的方法: defaultRallback");
        return GraceJsonResult.errorCustom(ResponseStatusEnum.SYSTEM_ERROR_GLOBAL);
    }


    @Override
    public GraceJsonResult getUserInfo(String userId) {
        AppUserInfoVO userInfo = userService.getBaseUserInfo(userId);
        return GraceJsonResult.ok(userInfo);
    }



    @Override
    public GraceJsonResult getCountInfo(String userId) {
        if (StringUtils.isBlank(userId)) {
            return GraceJsonResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }
        AppUser user = getUser(userId);
        UserAccountInfoVO userAccountInfoVO = new UserAccountInfoVO();
        BeanUtils.copyProperties(user,userAccountInfoVO);
        return GraceJsonResult.ok(userAccountInfoVO);

    }

    /**
     * 单独一个获得用户信息的方法
     * 由于用户信息更新频率不高，为了效率高所以把查询出来的用户信息存入redis中
     * TODO
     * @param userId
     * @return
     */
    private AppUser getUser(String userId) {
        AppUser user = null;
        //查询redis数据库中存不存在，如果存在查询返回出来
        String userjson = redis.get(REDIS_USER_INFO + ":" + userId);
        if (StringUtils.isNotBlank(userjson)) {
            user = JsonUtils.jsonToPojo(userjson, AppUser.class);
        }else{
            //如果redis中不存在，则从mysql中查询，查询出后再放进redis中
            user = appUserMapper.selectByPrimaryKey(userId);
            redis.set(REDIS_USER_INFO + ":" + userId,JsonUtils.objectToJson(user));
        }
        return user;
    }

    @Override
    public GraceJsonResult updateUserInfo(@Valid UpdateUserInfoBO updateUserInfoBO) {
        //校验BO
//        if (result.hasErrors()) {
//            Map<String, String> errors = getErrors(result);
//            return GraceJsonResult.errorMap(errors);
//        }
        //更新用户信息
        userService.updateUserInfo(updateUserInfoBO);
        return GraceJsonResult.ok();
    }

    @HystrixCommand//(fallbackMethod = "queryByIdsFollBack")
    @Override
    public GraceJsonResult queryByIds(String userIds) {
        if (StringUtils.isBlank(userIds)) {
            return GraceJsonResult.errorCustom(ResponseStatusEnum.USER_NOT_EXIST_ERROR);
        }
        //将idjson字符串列转为list类型
        List<String> publisherList = JsonUtils.jsonToList(userIds, String.class);
//        System.out.println("publisherList：*****"+publisherList);
        //FIXME :用于dev测试，硬编码用于抛出异常
//        if (publisherList.size() >1) {
//            System.out.println("发生异常了");
//            throw new RuntimeException("发生异常了");
//        }

        List<AppUserInfoVO> userInfoVOList = new ArrayList<>();
        for (String userId : publisherList) {
            AppUserInfoVO userInfoVO = getBaseUserInfoVO(userId);
//            System.out.println("userInfoVO : "+userInfoVO);
            //将用户信息添加到列表中
            userInfoVOList.add(userInfoVO);
        }
//        System.out.println("**********"+userInfoVOList.toString());
        return GraceJsonResult.ok(userInfoVOList);
    }

    /**
     * 服务降级的方法  userInfoVO设置为空
     * @param userIds
     * @return
     */
    public GraceJsonResult queryByIdsFollBack(String userIds) {
        System.out.println("使用降级的方法: queryByIdsFollBack");
        if (StringUtils.isBlank(userIds)) {
            return GraceJsonResult.errorCustom(ResponseStatusEnum.USER_NOT_EXIST_ERROR);
        }
        //将idjson字符串列转为list类型
        List<String> publisherList = JsonUtils.jsonToList(userIds, String.class);
        List<AppUserInfoVO> userInfoVOList = new ArrayList<>();
        for (String userId : publisherList) {
            AppUserInfoVO userInfoVO = new AppUserInfoVO();
            //将用户信息添加到列表中
            userInfoVOList.add(userInfoVO);
        }
        return GraceJsonResult.ok(userInfoVOList);
    }


    /**
     * 获取   AppUserInfoVO
     * @param userId
     * @return
     */
    private AppUserInfoVO getBaseUserInfoVO(String userId) {
        AppUser user = getUser(userId);
        AppUserInfoVO userInfoVO = new AppUserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }

}

